﻿using System;
using System.Collections.Generic;
using System.Linq;
using DotNetNuke.Entities.Portals;

namespace BrandonHaynes.Providers.ControlPanel
{
    /// <summary>
    /// Represents a binding between a control panel type and a set of roles
    /// (optionally circumscribed by portal)
    /// 
    /// If DotNetNuke.Framework.Providers.Provider had a better constructor I would just 
    /// use that as a base class.  Alas....
    /// </summary>
    public class ControlPanelMapping
        {
        /// <summary>
        /// The web.config key associated with the provider's type
        /// </summary>
        public const string TypeKey = "type";

        public ControlPanelMapping(string name, IDictionary<string, string> attributes)
            {
            Name = name;
            Attributes = attributes;
            }

        public string Name { get; private set; }
        public IDictionary<string, string> Attributes { get; private set; }

        public Type Type
            { get { return Type.GetType(Attributes[TypeKey]); } }

        /// <summary>
        /// The set of portals with which this provider is associated
        /// Expects a comma-separated list of portal ids in the configuration.
        /// </summary>
        public IEnumerable<int> Portals
            {
            get
                {
                string portals;
                return Attributes.TryGetValue(ControlPanelProvider.PortalKey, out portals)
                    ? portals.Split(',').Select(int.Parse)
                    : new PortalController().GetPortals().Cast<PortalInfo>().Select(portal => portal.PortalID);
                }
            }

        /// <summary>
        /// The set of roles with which this provider is associated.
        /// Expects a comma-separated list of roles in the configuration.
        /// </summary>
        public IEnumerable<string> Roles
            {
            get { 
                string roles;
                return Attributes.TryGetValue(ControlPanelProvider.RoleKey, out roles)
                    ? roles.Split(',') : Enumerable.Empty<string>();
                }
            }
        }
    }